// Token服务
export class TokenService {
    constructor() {
        this.setupMessageListener();
    }

    setupMessageListener() {
        window.addEventListener('message', (event) => {
            // 确保消息来源是可信的
            if (event.origin !== 'https://test-tds-standard.cepin.com') {
                return;
            }

            if (event.data.type === 'SET_TOKEN') {
                this.setToken(event.data.token);
            }
        });
    }

    setToken(token) {
        if (token) {
            // 设置请求头中的token
            const headers = new Headers();
            headers.append('Authorization', `Bearer ${token}`);
            
            // 将headers应用到所有后续请求
            window.fetch = new Proxy(window.fetch, {
                apply: function(target, thisArg, argumentsList) {
                    const [resource, config = {}] = argumentsList;
                    config.headers = {
                        ...config.headers,
                        'Authorization': `Bearer ${token}`
                    };
                    return target.apply(thisArg, [resource, config]);
                }
            });
        }
    }
} 